﻿using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using SQLite;
namespace StockTradTest.Data
{
    public class InvestorDatabase
    {
        readonly SQLiteAsyncConnection _database;

        public InvestorDatabase(string dbPath)
        {
            _database = new SQLiteAsyncConnection(dbPath);
            _database.CreateTableAsync<Investor>().Wait();
            
        }
        public Task<Investor> GetInvestorAsync(int date)
        {
            if(date.ToString().Length == 8)
            {
                date = int.Parse(date.ToString().Substring(0, 6));
            }
            return _database.Table<Investor>()
                            .Where(i =>i.Date == date)
                            .FirstOrDefaultAsync();
        }

        public Task<List<Investor>> GetInvestorAsync(int startDate = 0, int endDate = int.MaxValue)
        {
            if(endDate == int.MaxValue  & startDate == 0)
            {
                return _database.Table<Investor>().
                ToListAsync();
            }
            return _database.Table<Investor>().
                Where(i => i.Date > startDate & i.Date < endDate).
                ToListAsync();
        }
        //股票顺序为0-count：最旧-最新
        public async Task<int> SaveAllInvestorAsync(List<Investor> investors, bool forceUpdate = false)
        {
            if (investors == null || investors.Count == 0) return 0;
            if(forceUpdate)
            {
                await _database.DeleteAllAsync<Investor>();
                return await _database.InsertAllAsync(investors);
            }
            //数据库中该股票信息
            var check = GetInvestorAsync().Result;
            if(check == null || check.Count == 0)
            {
                return await _database.InsertAllAsync(investors);
            }
            //数据库中最新的日期股票信息
            Investor upToDateInvestor = check[check.Count - 1];
            //从最新日期开始计算
            for (int i= 0; i < investors.Count;i++)
            {
                //从最新的开始比对
                if (investors[i].Date == upToDateInvestor.Date) 
                {
                        return await _database.InsertAllAsync(investors.GetRange(i + 1, investors.Count - i-1));
                }
            }
            return await _database.InsertAllAsync(investors);
        }
        public async Task<int> SaveInvestorAsync(Investor investor,bool forceUpdate = false)
        {
            var result = GetInvestorAsync(investor.Date).Result;
            if (result == null)
                return await _database.InsertAsync(investor);
            else if(forceUpdate)
            {
                await _database.DeleteAsync(result);
                return await _database.InsertAsync(investor);
            }

            return 0;
        }
    }
}
